<template>
  <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">
      设备查询
      <div class="department-top-btn">
        <a class="btn-default" @click="addDevice">新增设备</a>
        <a class="btn-default" :href="downloadAddress" download>下载全部</a>
        <a class="btn-default" @click="uploadDevice">批量新增</a>
        <a class="btn-default" href="resource/新增设备模板.xlsx" download>下载模板</a>
      </div>
    </div>
    <!-- 搜索框 -->
    <el-form ref="form" :model="form" label-width="80px" size="small">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="设备编号">
            <el-col>
              <el-input placeholder="请输入编号" v-model="form.equipmentId"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号">
            <el-col>
              <el-input placeholder="请输入详细的设备型号" v-model="form.equipmentModel"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="所属" prop="deptId">
            <areaSelect :selectModel="form.deptId" :areaIds="areaIds" @onAreaChange="onAreaChange" hideThird="true"></areaSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择场景" prop="moduleId">
            <sceneSelect :selectModel="form.moduleId" :modTypes="modTypes" @onSceneChange="onSceneChange" :deptId="form.deptId"></sceneSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="el-form-item-multi clearfix">
        <el-row :gutter="15">
          <!--<el-col :span="12">-->
          <!--<el-form-item label="设备类型" prop="equipmentType">-->
          <!--<deviceTypeSelect :selectModel="form.equipmentType" @onDeviceChange="onDeviceChange"></deviceTypeSelect>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="6">
            <el-form-item label="设备状态">
              <el-col>
                <el-select v-model="form.equipmentState" placeholder="请选择设备状态">
                  <el-option v-for="item in stateArr" :key="item.value" :value="item.value" :label="item.name"></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="15">
        <el-form-item style="padding-left:15px">
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
          <!--<el-button>重置</el-button>-->
        </el-form-item>
      </el-row>
    </el-form>
    <!-- 列表 -->
    <el-table :data="tableData" stripe border class="el-table-body" v-if="showList">
      <el-table-column prop="equipmentId" label="设备编号" min-width="130">
      </el-table-column>
      <el-table-column prop="moduleName" label="场景" min-width="120">
        <!--<template slot-scope="scope">-->
        <!--<el-button type="text" size="small" @click.native="handleView(scope.$index,scope.row)">{{scope.row.equipmentName}}</el-button>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column prop="areaName" label="所属" min-width="150">
      </el-table-column>
      <el-table-column prop="equipmentModel" label="设备型号">
      </el-table-column>
      <el-table-column prop="equipmentState" :formatter="equipmentStateToText" label="设备状态" min-width="80">
      </el-table-column>
      <el-table-column prop="equipmentAddr" label="地址" min-width="180">
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="130">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope.$index, scope.row)">查看详情</el-button>
          <el-button type="text" size="small" @click.stop="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button type="text" size="small" @click.stop="handleClose(scope.$index, scope.row)">{{ scope.row.equipmentState === 0 ? '开启' : '关闭' }}
          </el-button>
          <el-button type="text" size="small" @click.stop="handleCloseVoice(scope.row)">消音</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background @current-change="changeEventTable" :current-page.sync="form.page" :page-size="form.limit" layout="total, prev, pager, next,jumper" :total="totalCount" class="el-page-body" v-if="showList">
    </el-pagination>
    <el-dialog title="批量新增" :visible.sync="dialogVisible" width="40%" :before-close="dialogClose">
      <el-form ref="form" label-width="80px">
        <div class="file-upload-box">
          <label>模板上传</label>
          <div class="form-item-content">
            <input v-model="uploadPath" class="text-input" />
            <input class="file-input" type="file" @change="uploadFileEvent" />
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click.native="dialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import areaSelect from '../../components/common/select/area'
import sceneSelect from '../../components/common/select/scene'
import deviceTypeSelect from '../../components/common/select/deviceType'

export default {
  name: 'deviceSearch',
  components: {
    areaSelect,
    sceneSelect,
    deviceTypeSelect
  },

  data () {
    return {
      gHeight: this.$store.state.gHeight,
      areaIds: {
        areaId1: '', // 所属1级
        areaId2: '', // 所属2级
        areaId3: '' // 所属3级
      },
      sceneList: [],
      modTypes: {
        modType1: '', // 场景分类
        modType2: '' // 场景子分类
      },
      deviceTypes: '',
      form: {
        equipmentId: '', // 事件编号
        deptId: '', // 所属
        moduleId: '', // 场景类型
        equipmentState: '', // 处理状态
        equipmentType: '', // 设备类型
        equipmentModel: '', // 设备型号
        page: 1,
        limit: 10
      },
      totalCount: 0, // 总数
      tableData: [], // 列表数据
      stateArr: [],
      dialogVisible: false, // 模板上传状态
      downloadAddress: '', // xlsx下载地址
      uploadPath: '',
      uploadFileObj: '',
      showList: true // 展示列表
    }
  },

  beforeRouteLeave (to, from, next) {
    if (to.name !== 'deviceView' && to.name !== 'deviceEdit') {
      this.$store.commit('keepOut')
    }
    next()
  },
  beforeRouteEnter (to, from, next) {
    if (from.name === 'deviceEdit') {
      next(vm => {
        vm.refreshTable()
      })
    }
    next(vm => {
      vm.$store.commit('keepIn', 'deviceSearch')
    })
  },

  mounted: function () {
    this.init()
  },

  methods: {
    // 页面初始方法
    init () {
      this.stateArr = this.$base.getConst('select', 'deviceState')
      let userInfoRes = JSON.parse(this.$base.getSessionStorage('userInfo'))
      let currentUserRole = userInfoRes.userRole
      if (currentUserRole !== 1) {
        this.refreshTable()
      } else {
        this.showList = false
      }
      this.downloadAddress =
        this.$base.getUrl('downLoadEquipmentInfo') +
        '?token=' +
        this.$base.getSessionStorage('token')
    },
    // 操作设备冻结
    handleClose (index, row) {
      let that = this
      let url = this.$base.getUrl('frozen')
      let data = {
        equipmentNo: row.equipmentNo
      }
      let params = {
        url: url,
        data: data
      }

      this.$confirm(' 是否冻结该设备?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.$store.dispatch('getForm', params).then(res => {
            if (res.code === 0) {
              this.$message({ type: 'success', message: '冻结成功!' })
            } else {
              this.$message({ type: 'error', message: res.msg })
            }
          })
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消删除' })
        })
    },
    uploadDevice () {
      let that = this
      that.dialogVisible = true
    },
    uploadFileEvent (e) {
      let that = this
      let files = e.target.files[0]
      let name = files.name
      that.uploadFileObj = files
      let ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
      if (ext === 'xls' || ext === 'xlsx') {
        if (typeof files === 'undefined' || files.size <= 0) {
          that.$message.error('请选择模板!')
          return false
        } else {
          that.uploadPath = name
        }
      } else {
        that.$message.error('上传的模板文件格式错误(xls或者xlsx)!')
      }
    },
    dialogSubmit () {
      let that = this
      let files = that.uploadFileObj
      if (files.length === 0) {
        that.$message.error('请选择模板!')
      } else {
        let name = files.name
        let ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
        if (ext === 'xls' || ext === 'xlsx') {
          if (typeof files === 'undefined' || files.size <= 0) {
            that.$message.error('请选择模板!')
            return false
          } else {
            that.fileUploadFun(files)
          }
        } else {
          that.$message.error('上传的模板文件格式错误(xls或者xlsx)!')
        }
      }
    },
    fileUploadFun (fileObj) {
      let that = this
      let param = new FormData()
      param.append('file', fileObj, fileObj.name)
      let url = this.$base.getUrl('upLoadEquipmentInfo')
      let params = {
        url: url,
        data: param
      }
      that.$store.dispatch('postUploadForm', params).then(res => {
        if (res.code === 0) {
          that.$message.success('模板上传成功！')
        } else if (res.code === 500) {
          that.$message.error(res.msg)
        }
      })
    },
    addDevice () {
      this.$router.push({ name: 'deviceEdit' })
    },
    handleEdit (index, row) {
      this.$router.push({
        name: 'deviceEdit',
        query: {
          id: row.equipmentNo
        }
      })
    },
    handleCloseVoice (row) {
      let url = this.$base.getUrl('jiaCancelSmoke')
      let params = {
        url: url,
        data: {
          equipmentId: row.equipmentId
        }
      }
      this.$store.dispatch('getForm', params).then((res) => {
        console.log(res)
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '消音成功!'
          })
        }
      })
    },
    handleView (index, row) {
      this.$router.push({
        name: 'deviceView',
        query: {
          id: row.equipmentNo
        }
      })
    },
    onSubmit: function () {
      this.form.page = 1
      this.refreshTable()
      // this.$router.replace({name: 'eventSearch', query: this.form})
    },
    // 设备状态转换成文字
    equipmentStateToText: function (row) {
      return this.$base.getNameByConst(
        'select',
        'deviceState',
        row.equipmentState
      )
    },
    // 切换页码
    changeEventTable: function (val) {
      this.form.page = val
      this.refreshTable()
      // this.$router.replace({name: 'eventSearch', query: this.form})
    },
    // 拉取表格信息
    refreshTable: function () {
      this.showList = true
      let _this = this
      let url = this.$base.getUrl('getList')
      let params = {
        url: url,
        data: this.form
      }
      this.$store.dispatch('getForm', params).then(res => {
        let data = res
        if (data.list) {
          _this.tableData = data.list
        } else {
          _this.tableData = []
        }
        _this.totalCount = data.totalCount
      })
    },
    // getSceneByAreaId (areaId) {
    //   let url = this.$base.getUrl('getModuleInfoTree')
    //   let params = {
    //     url: url,
    //     data: {
    //       deptId: areaId
    //     }
    //   }
    //   this.$store.dispatch('getForm', params).then(res => {
    //     this.sceneList = res.nodes
    //     this.modTypes.modType1 = ''
    //     this.modTypes.modType2 = ''
    //   })
    // },
    // 所属变化时
    onAreaChange (val) {
      // this.getSceneByAreaId(val)
      this.form.deptId = val
    },
    onSceneChange (val) {
      this.form.moduleId = val
    },
    onDeviceChange (val) {
      this.form.equipmentType = val
    },
    // 关闭弹窗
    dialogClose () {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.file-upload-box {
  height: 40px;
  line-height: 40px;
  position: relative;
}

.file-upload-box label {
  text-align: right;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 80px;
}

.form-item-content {
  margin-left: 80px;
  line-height: 40px;
  position: relative;
  font-size: 14px;
}

.form-item-content .text-input,
.form-item-content .file-input {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
  cursor: pointer;
}

.form-item-content .file-input {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  opacity: 0;
}

.g-content-title {
  position: relative;
  padding-right: 20px;
}

.department-top-btn {
  float: right;
}

.department-top-btn .btn-default {
  display: inline-block;
  padding: 2px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  cursor: pointer;
  background: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-left: 6px;
  text-decoration: none;
  color: #333;
}

.el-table {
  width: auto !important;
  text-align: center;
  margin: 10px;
}

.el-table >>> th {
  text-align: center;
}

.el-pagination {
  margin: 0 10px;
}

.el-dialog__wrapper >>> .pic-popup {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: auto;
  margin: 0;
}

.el-dialog__wrapper >>> .el-dialog__body {
  padding: 20px;
}

.el-dialog__wrapper >>> .el-dialog__header {
  padding: 10px 20px 10px;
}

.el-dialog__wrapper >>> .el-dialog__headerbtn {
  top: 10px;
}
</style>
